import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

import styles from '../styles/Search.module.scss'
import { useEffect, useRef, useState } from 'react'
import { List, Space, Tag, Image, Ellipsis, InfiniteScroll } from 'antd-mobile'

import Searchbar from '../components/Searchbar'
import router from 'next/router'
import Back from '../components/Back'
import { BookService } from '../services'
import { Blist } from '../services/book.service'
import Empty from '../components/Empty'
import { judgeLoad, uniqueFunc } from '../libs/utils'

interface Props {
  books: Blist[],
  total: number,
  stats: boolean,
  major?: string[]
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const { major } = ctx.query
  if (major) {
    const temp = typeof (major) === 'string' ? [major] : major as string[]
    const res = await BookService.searchlist(false, 0, 10, temp)
    if (res.stat === 'OK')
      return {
        props: {
          books: res.data.list,
          total: res.data.total,
          stats: true,
          major: temp
        }
      }
  }
  return {
    props: {
      books: [],
      total: 0,
      stats: false
    }
  }
}

const pageSize = 10

const SearchPage: NextPage<Props> = ({ books, stats, major }) => {

  const [goSearch, setGoSearch] = useState(stats)
  const [hasMore, setHasMore] = useState(true)
  const [active, setActive] = useState(true)
  const [booklist, SetBooks] = useState(books)
  const [text, setText] = useState('')

  async function getList(flag: boolean, offset: number, major?: string[], text?: string) {
    const str = text?.replace(/\s*/g, "")
    const search = str === '' ? undefined : str
    const res = await BookService.searchlist(flag, offset, pageSize, major, search)

    if (res.stat === 'OK') {
      const newList = res.data.list
      SetBooks(oldList => {
        const total = oldList.length + newList.length
        setHasMore(total < res.data.total)
        return uniqueFunc([...oldList, ...newList]) as BookService.Blist[]
      })
    } else setHasMore(false)
  }

  const befActive = useRef(active)
  useEffect(() => {
    async function getDate() {
      const str = text?.replace(/\s*/g, "")
      const search = str === '' ? undefined : str
      const res = await BookService.searchlist(active, 0, pageSize, major, search)
      if (res.stat === 'OK') SetBooks(res.data.list)
    }
    if (befActive.current !== active) {
      befActive.current = active
      getDate()
      setHasMore(true)
    }
  }, [active, major, text])

  useEffect(() => {
    setText('')
  }, [major])

  useEffect(() => {
    SetBooks(books);
  }, [books])

  return (
    <div className="page">
      <Head>
        <title>搜索</title>
      </Head>
      <div className={styles.wrap}>
        <Searchbar page='search' send={(v: string) => {
          SetBooks([])
          setText(v)
          getList(active, 0, major, v)
          setGoSearch(true)
        }} />
        {!goSearch && <div className={styles.tacitly}>
          <main>
            <div className={styles.fenlei}>
              <h3 className={styles.title}>
                小民推荐
              </h3>
              <ul className={styles.shudan}>
                <li>公选有你</li>
                <li>必修有你</li>
                <li>专业选修</li>
                <li>计科电信</li>
                <li>考研书单</li>
              </ul>
            </div>
            <div className={styles.fenlei}>
              <h3 className={styles.title}>
                学长推荐?
              </h3>
              <ul className={styles.shudan}>
                <li>大一书籍</li>
                <li>大二有用</li>
                <li>大三考研</li>
                <li>大四实习</li>
                <li>大五...</li>
              </ul>
            </div>
          </main>
        </div>}
        {goSearch && <div className={styles.res}>
          <div className={styles.header}>
            <span>搜索结果</span>
            <ul>
              <li
                className={active ? styles.bule : ' '}
                onClick={() => setActive(true)}>最新</li>
              <li
                className={active ? ' ' : styles.bule}
                onClick={() => setActive(false)}>最热</li>
            </ul>
          </div>
          <List header={null}>
            {
              booklist?.map(book =>
                <List.Item
                  arrow={false}
                  key={book._id}
                  onClick={() => router.push(`/goods/${book._id}`)}
                  extra={<>
                    <span className='price'>{(book.lowprice).toFixed(2)}</span>
                  </>}
                  description={
                    <Ellipsis direction='end' rows={2} content={'简介: ' + book.content} />
                  }
                  title={
                    <Space>
                      <Tag color='default'>{book.major[0]}</Tag>
                      {book.major[1] && <Tag color='success'>{book.major[1]}</Tag>}
                    </Space>
                  }
                  prefix={
                    <div className={styles.img}>
                      <Image alt='' src={book.banner[0]} fit='cover'
                        width={60} height={80} />
                    </div>
                  }
                >
                  <span>{book.title}</span>
                </List.Item>
              )
            }
            {booklist.length === 0 && <Empty />}
            {
              !judgeLoad(books, hasMore) &&
              <InfiniteScroll
                loadMore={async () => await getList(active, booklist.length, major, text)}
                hasMore={hasMore}
              />
            }
          </List>
        </div>}
        <Back />
      </div>
    </div >
  )
}

export default SearchPage
